package com.twd.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Chris Chan
 * Create on 2021/4/20 13:58
 * Use for:
 * Explain:
 */
public class WebsocketConnectHandler extends ChannelInboundHandlerAdapter {
    private String path = "/";

    public static void main(String[] args) {
        String s = get();
        System.out.println(s+"====");
    }

    public static  String get(){

        try {
            return ""+10/0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "as";
    }
    public WebsocketConnectHandler(String path) {
        this.path = path;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest httpRequest = (FullHttpRequest) msg;
            String uri = httpRequest.uri();

            String origin = httpRequest.headers().get("Origin");
            if (null == origin) {
                ctx.close();
            } else {
                if (null != uri && uri.contains(path)) {
                    String[] split = uri.split("/");
                    if (split.length == 4) {
                        String username = split[2];
                        String groupid = split[3];
                        String info = username + " 上线 大家欢迎 目前在线 " + (ClientManager.size() + 1) + "人";
                        System.out.println(info);
                        ClientManager.addChannel(username, ctx.channel(),Integer.parseInt(groupid));
                        ClientManager.send(info,ctx.channel().id());
                    }
                    httpRequest.setUri(path);
                }
            }
        }
        super.channelRead(ctx, msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String username = ClientManager.getUsername(ctx.channel());
        ClientManager.removeChannel(ctx.channel().id());
        String info = username + " 下线 目前在线 " + ClientManager.size() + " 人";

        System.out.println(info);
        ClientManager.send(info, ctx.channel().id());
    }
}